﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Csla;
using lite;
using OpenExpressApp.DB.Utils;
using OpenExpressApp.MetaAttribute;
using OpenExpressApp.MetaModel.Audit;
using OpenExpressApp.Types;
using System.Diagnostics;

namespace OpenExpressApp.Library.Audit
{
    [Serializable]
    public partial class AuditItemList : GBusinessListBase<AuditItemList, AuditItem>
    {
        #region  Factory Methods

        public static AuditItemList GetList()
        {
            return DataPortal.Fetch<AuditItemList>();
        }

        public static AuditItemList GetList(AuditItemConditionCriteria criteria)
        {
            return DataPortal.Fetch<AuditItemList>(criteria);
        }

        private AuditItemList()
        {
            AllowNew = true;
        }

        #endregion

        protected override object AddNewCore()
        {
            var item = AuditItem.New();
            Add(item);
            return item;
        }

        #region  Data Access

        private void DataPortal_Fetch()
        {
            RaiseListChangedEvents = false;

            using (var db = DBHelper.CreateDb(ConnectionStringNames.OpenExpressApp))
            {
                IQuery q = db.Query().Order("LogTime", false);
                var list = db.Select<AuditItem>(q);
                foreach (var item in list)
                {
                    this.Add(AuditItem.Get(item));
                }
            }

            RaiseListChangedEvents = true;
        }

        private void DataPortal_Fetch(AuditItemConditionCriteria criteria)
        {
            RaiseListChangedEvents = false;

            using (var db = DBHelper.CreateDb(ConnectionStringNames.OpenExpressApp))
            {
                //拼装查询条件
                IQuery q = db.Query()
                    .Constrain("Title").Like(criteria.TitleKeyWords)
                    .And().Constrain("Content").Like(criteria.ContentKeyWords)
                    .And().Constrain("User").Like(criteria.UserKeyWords)
                    .And().Constrain("MachineName").Like(criteria.MachineKeyWords);
                //起始时间和终止时间只精确到日。终止时间往后推一天
                q.And().Constrain("LogTime").GreaterEqual(criteria.StartTime.Date);
                q.And().Constrain("LogTime").LessEqual(criteria.EndTime.AddDays(1d).Date);
                if (string.IsNullOrEmpty(criteria.ModuleName) == false)
                {
                    q.And().Constrain("ModuleName").Equal(criteria.ModuleName);
                }
                if (criteria.AuditLogType != AuditLogType.None)
                {
                    q.And().Constrain("Type").Equal(criteria.AuditLogType);
                }

                q.Order("LogTime", false);

                //查询数据
                var list = db.Select<AuditItem>(q);
                foreach (var item in list)
                {
                    this.Add(AuditItem.Get(item));
                }
            }

            RaiseListChangedEvents = true;
        }

        #endregion
    }

    [Serializable]
    [Table]
    [DefaultObject("890a240e-227e-497b-a748-d122703cc406", Catalog = "用户权限", ModuleType = ModuleType.List, Index = 4), Label("日志管理")]
    [CondtionQueryType(typeof(AuditItemConditionCriteria))]
    [NotAllowEdit, NotAllowNew]
    public partial class AuditItem : GBusinessBase<AuditItem>
    {
        #region  Business Properties

        private static PropertyInfo<Guid> IdProperty =
            RegisterProperty(new PropertyInfo<Guid>("Id"));
        [System.ComponentModel.DataObjectField(true, true)]
        [Column, PK]
        [EntityProperty]
        [Indexable(IndexModeEnum.IndexModeAlways)]
        public Guid Id
        {
            get { return GetProperty(IdProperty); }
            set { SetProperty(IdProperty, value); }
        }

        private static PropertyInfo<string> TitleProperty =
          RegisterProperty(new PropertyInfo<string>("Title"));
        [Column]
        [EntityProperty]
        [Required, ShowInList, Label("标题")]
        public string Title
        {
            get { return GetProperty(TitleProperty); }
            set { SetProperty(TitleProperty, value); }
        }

        private static PropertyInfo<string> ContentProperty =
          RegisterProperty(new PropertyInfo<string>("Content"));
        [Column]
        [EntityProperty]
        [Required, ShowInList, Label("内容")]
        public string Content
        {
            get { return GetProperty(ContentProperty); }
            set { SetProperty(ContentProperty, value); }
        }

        private static PropertyInfo<string> UserProperty =
          RegisterProperty(new PropertyInfo<string>("User"));
        [Column]
        [EntityProperty]
        [Required, ShowInList, Label("用户")]
        public string User
        {
            get { return GetProperty(UserProperty); }
            set { SetProperty(UserProperty, value); }
        }

        private static PropertyInfo<string> MachineNameProperty =
          RegisterProperty(new PropertyInfo<string>("MachineName"));
        [Column]
        [EntityProperty]
        [Required, ShowInList, Label("机器名")]
        public string MachineName
        {
            get { return GetProperty(MachineNameProperty); }
            set { SetProperty(MachineNameProperty, value); }
        }

        private static PropertyInfo<string> ModuleNameProperty =
          RegisterProperty(new PropertyInfo<string>("ModuleName"));
        [Column]
        [EntityProperty]
        [Required, ShowInList, Label("模块名")]
        public string ModuleName
        {
            get { return GetProperty(ModuleNameProperty); }
            set { SetProperty(ModuleNameProperty, value); }
        }

        private static PropertyInfo<AuditLogType> TypeProperty =
          RegisterProperty(new PropertyInfo<AuditLogType>("Type"));
        [Column]
        [EntityProperty]
        [Required, ShowInList, Label("类型")]
        public AuditLogType Type
        {
            get { return GetProperty(TypeProperty); }
            set { SetProperty(TypeProperty, value); }
        }

        private static PropertyInfo<DateTime> LogTimeProperty =
          RegisterProperty(new PropertyInfo<DateTime>("LogTime"));
        [Column]
        [EntityProperty]
        [Required, ShowInList, Label("时间")]
        public DateTime LogTime
        {
            get { return GetProperty(LogTimeProperty); }
            set { SetProperty(LogTimeProperty, value); }
        }

        #endregion

        #region  Factory Methods

        private AuditItem() { }

        public static AuditItem New()
        {
            return DataPortal.Create<AuditItem>();
        }

        public static AuditItem Get(AuditItem data)
        {
            return DataPortal.Fetch<AuditItem>(data);
        }

        #endregion

        #region  Data Access

        [RunLocal]
        protected override void DataPortal_Create()
        {
            this.LoadProperty(IdProperty, Guid.NewGuid());
            this.LoadProperty(TitleProperty, string.Empty);
            this.LoadProperty(ContentProperty, string.Empty);
            this.LoadProperty(UserProperty, string.Empty);
            this.LoadProperty(MachineNameProperty, string.Empty);
            this.LoadProperty(ModuleNameProperty, string.Empty);
            this.LoadProperty(TypeProperty, AuditLogType.None);
            this.LoadProperty(LogTimeProperty, DateTime.Now);

            this.ValidationRules.CheckRules();
        }

        private void DataPortal_Fetch(AuditItem data)
        {
            this.Clone(data);
        }

        protected override void DataPortal_Insert()
        {
            using (var db = DBHelper.CreateDb(ConnectionStringNames.OpenExpressApp))
            {
                db.Insert(this);
                // update child objects
                FieldManager.UpdateChildren(this);
            }
        }

        protected override void DataPortal_Update()
        {
            using (var db = DBHelper.CreateDb(ConnectionStringNames.OpenExpressApp))
            {
                db.Update(this);
                // update child objects
                FieldManager.UpdateChildren(this);
            }
        }

        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(this.Id);
        }

        private void DataPortal_Delete(Guid id)
        {
            using (var db = DBHelper.CreateDb(ConnectionStringNames.OpenExpressApp))
            {
                db.Delete(typeof(AuditItem), db.Query().Constrain("Id").Equal(id));
            }
        }

        #endregion

        public void Clone(AuditItem target)
        {
            this.LoadProperty(IdProperty, target.Id);
            this.LoadProperty(TitleProperty, target.Title);
            this.LoadProperty(ContentProperty, target.Content);
            this.LoadProperty(UserProperty, target.User);
            this.LoadProperty(MachineNameProperty, target.MachineName);
            this.LoadProperty(ModuleNameProperty, target.ModuleName);
            this.LoadProperty(TypeProperty, target.Type);
            this.LoadProperty(LogTimeProperty, target.LogTime);
        }
    }
}